package com.moleq.dialog;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Formatter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.moleq.base.MoleQBaseDialog;
import com.moleq.base.OnResultListener;
import com.moleq.base.SmartBeep;
import com.moleq.mgpos.activities.NetworkSettingActivity;
import com.moleq.mgpos.activities.R;
import com.moleq.models.NetworkSetting;
import com.moleq.network.CommunicationCallback;
import com.moleq.network.ConnectHandler;
import com.moleq.service.ServiceManager;
import com.moleq.util.MoleQUtil;

public class NetworkListsDialog extends Dialog implements OnResultListener{

	private OnResultListener mOnResultListener;
	private Button mButtonCancel,mButtonOk,mButtonGo;
	private EditText mEditTextStart,mEditTextEnd;
//	private TextView tv_range;
//	private TransactionManager mPaymentMgr;
	private Context mContext;
	private ListView mListView;
	private List<NetworkSetting> mDataSource = new  ArrayList<NetworkSetting>();
	public NetworkListAdapter mAdapter;
	private int selectedRow = 0;
	private ConnectHandler mNetworkMonitor = null;
	private ProgressDialog mProcessingDlg;
	private AbsoluteLayout al_context;
	private WifiManager wifi_service = null;
	private String localIp = "";
	private EditText et_ip1;
	private EditText et_ip2;
	private EditText et_ip3;
	
	private CommunicationCallback mCmmCallback = new CommunicationCallback() {

		@Override
		public void onConnected(String ip) {
			// TODO Auto-generated method stub
//			System.out.println("return --> " + ip);
			NetworkSetting mNetworkSetting = new NetworkSetting();
			mNetworkSetting.setNs_ip(ip);
			mNetworkSetting.setOnline(true);
			mNetworkSetting.setNs_station(-1);
			mNetworkSetting.setNs_type("A");
			mDataSource.add(mNetworkSetting);
		}
		
		@Override
		public void onCheckNetworkStart() {
//			mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(1, ""));
		}

		@Override
		public void onCheckNetworkComplete() {
//			mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(0, ""));

//			mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(3, ""));

		}

		@Override
		public void onDisconnected(String ip) {
			Log.i("networksetting", ip + " is disconnected...");

		}


		@Override
		public void onError(String errMsg) {
			// TODO Auto-generated method stub
			
		}
		
	};
	
	private Button.OnClickListener mOnClickListener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {	
			
			switch(v.getId()){
			case R.id.btn_cancel:
				dispose();
				dismiss();
				break;
			case R.id.btn_ok:	
				if(mDataSource.size() <= 0){
					onCloseWithReturn(R.id.btn_ok,"");
				}
//				onCloseWithReturn(mDataSource.get(selectedRow));
//				dismiss();
				if(checkStation()){
					for (int i = 0; i < mDataSource.size(); i++) {
						if(mDataSource.get(i).getNs_station() > 0){
	//						System.out.println(mDataSource.get(i).getNs_ip());
							if(!ServiceManager.getInstance().mNetWorkSettingService.checkIp(mDataSource.get(i).getNs_ip())){
								ServiceManager.getInstance().mNetWorkSettingService.Insert(mDataSource.get(i));
							}
						}
					}
					onCloseWithReturn(R.id.btn_ok,"");
				}
				
				break;
			case R.id.btn_go:
				Keyboard();
				mDataSource.clear();
				mAdapter.notifyDataSetChanged();
				
				if(validation()){
					String start = mEditTextStart.getText().toString();
					String end = mEditTextEnd.getText().toString();
//					final String range = tv_range.getText().toString();
					final String range = et_ip1.getText()+"."+ et_ip2.getText()+"."+ et_ip3.getText()+".";
					final int s = Integer.valueOf(start);
					final int e = Integer.valueOf(end);
					mProcessingDlg = new ProgressDialog(mContext);
					mProcessingDlg.setTitle("");
					mProcessingDlg.setMessage("Scanning, please wait...");
					mProcessingDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					mProcessingDlg.getWindow().setWindowAnimations(android.R.style.Animation);
					mProcessingDlg.setCancelable(true);
					int count = e - s + 1;
					mProcessingDlg.setMax(count);
					mProcessingDlg.setProgress(0);
					mProcessingDlg.setButton("Cancel", new DialogInterface.OnClickListener() {
						 public void onClick(DialogInterface dialog, int i) {
							 mNetworkMonitor.action = false;
							 dialog.cancel();
						 }
					});  
					mProcessingDlg.show();
					mNetworkMonitor.action = true;
				
					new Thread() {
						public void run() {
							
							for (int j = s; j <= e; j++) {

								if(mNetworkMonitor.action){
									String ip = range + j;
//									String ip = "192.168.1." + j;
//									String aaString = range;
									mNetworkMonitor.connect(ip);
									mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(1, ""));
									mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(3, ""));
								}
							}
							mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(0, ""));
							
						};
					}.start();
				}
				
				break;
			case R.id.al_context:
				Keyboard();
				break;
			}
		}
	};
	
	public ListView.OnItemClickListener onItemClickListener = new ListView.OnItemClickListener() {


		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			switch (parent.getId()) {
			case R.id.lv_station:
				ScrollToRow(position);
				break;
			}
		}
	};
	
	public View.OnClickListener mlistener = new View.OnClickListener(){

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
		}
		
	};
	
	public void onCloseWithReturn(int whatid,Object obj){
		mOnResultListener.onReturnValue(whatid,obj);
		dismiss();
	}
	
	public NetworkListsDialog(Context context) {
//		super(context);
		super(context,R.style.dialog2);
		constructor(context);
		
	}
	public NetworkListsDialog(Context context, Object base,WifiManager wifi) {
		super(context,R.style.dialog2);
		wifi_service = wifi;
		constructor(context,base);
	}
	
	private void constructor(Context context,Object base) {
		mContext = context;
//		nsa = (NetworkSettingActivity)mContext;
		mOnResultListener = (OnResultListener) base;
	}

	public NetworkListsDialog(Context context, int theme) {
		super(context, theme);
		
		constructor(context);
	}
	
	private void constructor(Context context) {
		// TODO Auto-generated method stub
		mContext = context;
	}
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// set UI layout
		this.setContentView(R.layout.dialog_perview_network_list);
		this.setCancelable(false);
	
		mButtonCancel = (Button) findViewById(R.id.btn_cancel);
		mButtonCancel.setOnClickListener(mOnClickListener);
		
		mButtonOk = (Button) findViewById(R.id.btn_ok);
		mButtonOk.setOnClickListener(mOnClickListener);
		
		mButtonGo = (Button) findViewById(R.id.btn_go);
		mButtonGo.setOnClickListener(mOnClickListener);

		mListView = (ListView) findViewById(R.id.lv_station);
		mListView.setOnItemClickListener(onItemClickListener);
		
		mEditTextStart = (EditText) findViewById(R.id.et_ip_start);
		mEditTextEnd = (EditText) findViewById(R.id.et_ip_end);
		al_context = (AbsoluteLayout) findViewById(R.id.al_context);
		al_context.setOnClickListener(mOnClickListener);
//		tv_range = (TextView) findViewById(R.id.tv_range);
		et_ip1 = (EditText) findViewById(R.id.et_ip1);
		et_ip2 = (EditText) findViewById(R.id.et_ip2);
		et_ip3 = (EditText) findViewById(R.id.et_ip3);
		if (wifi_service!= null && wifi_service.isWifiEnabled()) {
			localIp = getWifiLocalIpAddress();
		}else{
			localIp = getLocalIpAddress();
		}
//		String[] ipList = localIp.split("\\.");
//		tv_range.setText(ipList[0] + "." + ipList[1] + "." + ipList[2] + ".");

		
		mAdapter = new NetworkListAdapter(mContext);
		mListView.setAdapter(mAdapter);
//		mListView.setDivider(null);
		
		mNetworkMonitor = new ConnectHandler(6677, mCmmCallback);
	}
	
	public void show(){
		super.show();		
//		mPaymentMgr =  TransactionManager.getInstance();
		
//		mDataSource =  ServiceManager.getInstance().mDepartmantService.FindAll();
//		if (mDataSource.size() <= 0) {
//			Departmant dep = new Departmant();
//			dep.setDep_name("Department1");
//			dep.setDep_no(1);
//			mDataSource.add(dep);
//		}
//		mAdapter.notifyDataSetChanged();
	}
	
	class NetworkListAdapter extends BaseAdapter{
		private Context maContext;
		public final class ViewHolder{
			public TextView tv_station_ip;
			public EditText et_station_no;
		}
		
		public NetworkListAdapter(Context context){
			maContext = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mDataSource.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mDataSource.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			
			if(convertView == null){
				holder = new ViewHolder();
				
				convertView = LayoutInflater.from(maContext).inflate(R.layout.network_station_item, null);
				holder.tv_station_ip = (TextView) convertView.findViewById(R.id.tv_station_ip);
				holder.et_station_no = (EditText) convertView.findViewById(R.id.et_station);
				holder.et_station_no.addTextChangedListener(new bAmtTextWatcher(holder));
//				convertView.setOnTouchListener(onItemTouchListener);
				convertView.setTag(holder);
			}else{
				holder = (ViewHolder) convertView.getTag();
			}
			
			
			if(localIp.equals(mDataSource.get(position).getNs_ip())){
				holder.tv_station_ip.setText("*" + mDataSource.get(position).getNs_ip());
				holder.et_station_no.setTag(position);
			}else{
				holder.tv_station_ip.setText(mDataSource.get(position).getNs_ip());
				holder.et_station_no.setTag(position);
			}
			
			
//			if(position == selectedRow){
//				holder.tv_dep_name.setBackgroundColor(Color.rgb(255,219,16));
//			}else{
//				holder.tv_dep_name.setBackgroundColor(Color.rgb(204, 204, 204));
//			}
//			
			return convertView;
		}
		
		class bAmtTextWatcher implements TextWatcher{
			private ViewHolder mHolder;
			
			public bAmtTextWatcher(ViewHolder holder) {
				// TODO Auto-generated constructor stub
				mHolder = holder;
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				int position = (Integer) mHolder.et_station_no.getTag();
				String ip = mDataSource.get(position).getNs_ip();
				if (s != null && !"".equals(s.toString())) {
					mDataSource.get(position).setNs_station(Integer.valueOf(s.toString()));
					mDataSource.get(position).setNs_name("Station " + s.toString());
				}else{
					mDataSource.get(position).setNs_station(-1);
					mDataSource.get(position).setNs_name("");
				}
				
			}
			
		}
		
	}
	
	private OnTouchListener onItemTouchListener = new OnTouchListener(){

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if(event.getAction() == MotionEvent.ACTION_DOWN){
				SmartBeep.getInstance().play(SmartBeep.SOUND_CLICK);
			}
			return false;
		}
		
	};
	
	public void ScrollToRow(int row){
		selectedRow = row;
		mAdapter.notifyDataSetChanged();
	}
	
	private void dispose() {
		// TODO Auto-generated method stub
		if (mNetworkMonitor != null) {
			mNetworkMonitor.release();
		}

	}
	
	public boolean validation() {
		String startIp = mEditTextStart.getText().toString();
		String endIp = mEditTextEnd.getText().toString();
		
//		if (startIp.equals("")) {
//			MessageBox.show(mContext, "Start Ip address cannot be empty.");
//			return false;
//		}
//		
//		if (endIp.equals("")) {
//			MessageBox.show(mContext, "End Ip address cannot be empty.");
//			return false;
//		}
//
//		if(Integer.valueOf(startIp) > Integer.valueOf(endIp)){
//			MessageBox.show(mContext, "Start IP must be smaller than the end IP.");
//			return false;
//		}
//		
//		if(Integer.valueOf(startIp) > 255){
//			MessageBox.show(mContext, "IP range cannot be greater than 255.");
//			return false;
//		}
//		
//		if(Integer.valueOf(endIp) > 255){
//			MessageBox.show(mContext, "IP range cannot be greater than 255.");
//			return false;
//		}
		
		if (startIp.equals("") || endIp.equals("") || (Integer.valueOf(startIp) > Integer.valueOf(endIp)) || Integer.valueOf(startIp) > 255 || Integer.valueOf(endIp) > 255) {
			MessageBox.show(mContext, "Invalid IP Range.");
			return false;
		}
		String ip = et_ip1.getText()+"."+ et_ip2.getText()+"."+ et_ip3.getText()+"."+startIp;
		if (!MoleQUtil.checkIp(ip)) {
			MessageBox.show(mContext, "Invalid IP address.");
			return false;
		}
		
		
		return true;
	}
	
	public boolean checkStation(){
		if(mDataSource == null || mDataSource.size() <= 0){
			return false;
		}else{
			for (int i = 0; i < mDataSource.size(); i++) {
				NetworkSetting mNetworkSetting = mDataSource.get(i);
				if(mNetworkSetting.getNs_station() > 0){
					for (int j = 0; j < mDataSource.size(); j++) {
						if (!mNetworkSetting.getNs_ip().equals(mDataSource.get(j).getNs_ip()) && (mNetworkSetting.getNs_station() == mDataSource.get(j).getNs_station())) {
							MessageBox.show(mContext, "Station " + mNetworkSetting.getNs_station() + " already exists.");
							return false;
						}
					}
				}
			}
			return true;
		}
	}
	
	private Handler mNetworkhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				Log.i("networksetting", " dismiss processing dialog -> ");
				if (mProcessingDlg != null || mProcessingDlg.isShowing()) {
					mProcessingDlg.dismiss();
				}
				break;
			case 1:
				mProcessingDlg.incrementProgressBy(1);
				break;
			case 2:
//				mNetworkhandler.removeCallbacks(test);
				break;
			case 3:
				mAdapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void onCloseWithReturn(Class<? extends MoleQBaseDialog> pramClass,
			int viewId, String returnvalue) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onReturnValue(int what, Object obj) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onShowingMessageDlg(boolean isShowing) {
		// TODO Auto-generated method stub
		
	}

	public String getWifiLocalIpAddress() {
		String wifilocalIpAddress = null;
		
		WifiInfo wifiinfo = wifi_service.getConnectionInfo();
		wifilocalIpAddress =  Formatter.formatIpAddress(wifiinfo.getIpAddress());
		
		return wifilocalIpAddress;
	}
	
	public String getLocalIpAddress() {
		String localIpAddress = null;
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						localIpAddress = inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("WifiPreference IpAddress", ex.toString());
		}
		
		return localIpAddress;
	}
	
	public String getLocalMacAddress() {     
        WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);     
        WifiInfo info = wifi.getConnectionInfo();     
        return info.getMacAddress();     
    }     
	
	public void Keyboard(){
		InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(NetworkListsDialog.this
				.getCurrentFocus().getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}

	

}
